package org.example.leetCode;

/**
 * @author Administrator
 */
public class SortedArrayToBST {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null) {
            return null;
        }
        return buildTree(nums, 0, nums.length - 1);
    }

    private TreeNode buildTree(int[] nums, int i, int i1) {
        if (i > i1) {
            return null;
        }
        int m = i + (i1 - i) / 2;
        TreeNode treeNode = new TreeNode(nums[m]);
        treeNode.left = buildTree(nums, i, m - 1);
        treeNode.right = buildTree(nums, m + 1, i1);
        return treeNode;
    }
}
